package com.jlt.baidu.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;

/**
 * 从数据库中生成标准json，中英文两份文档,数据来源从4.1_jlt_pms数据库取值
 * 
 * @author 苹果
 * @date 2019/10/18
 */
@Slf4j
@Component
public class StandardLocaltionUtil {
    private static final String FILE_PATH = "\\src\\main\\resources\\";

    /**
     * 将对象序列化成json，生成json文档
     * 
     * @param resultModel
     */
    public void serialJsonFile(List<LocaltionJsonModel> resultModel) {
        String jsonResult = JSON.toJSONString(resultModel);
        String basePath = System.getProperty("user.dir");
        try {
            String filePath = basePath + FILE_PATH;
            log.info(String.format("文件路径：%s", filePath));
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            PrintWriter write = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
            BufferedWriter out = new BufferedWriter(write);
            out.write(jsonResult);;
            out.flush();
            write.close();
            out.close();
        } catch (FileNotFoundException e) {
            log.error("找不到相应路径文件:", e);
        } catch (IOException e) {
            log.error("文件输出流错误:", e);
        }
    }

    public List<LocaltionJsonModel> readJsonFile(String fileName) {
        List<LocaltionJsonModel> jsonResult = new ArrayList<>();
        try {
            ClassPathResource classPathResource = new ClassPathResource(fileName);
            InputStream inputStream = classPathResource.getInputStream();
            InputStreamReader input = new InputStreamReader(inputStream, "utf-8");
            BufferedReader read = new BufferedReader(input);
            StringBuilder result = new StringBuilder();
            String tmpConten = null;
            while ((tmpConten = read.readLine()) != null) {
                result.append(tmpConten);
            }
            input.close();
            read.close();
            // 转化为对象
            jsonResult = JSON.parseArray(result.toString(), LocaltionJsonModel.class);
        } catch (UnsupportedEncodingException | FileNotFoundException e) {
            log.info("读取json文件错误：文件未找到", e);
        } catch (IOException e) {
            log.info("读取json文件错误：IO错误", e);
        }
        return jsonResult;
    }

}
